package com.ruoyi.generator.util;


import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.generator.word.WordTemplateFillData;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import com.ruoyi.common.constant.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * VelocityEngine工厂
 *
 * @author RuoYi
 */
public class WordUtils
{
    protected  static  final Logger logger = LoggerFactory.getLogger(WordUtils.class);



    public static <T> String createWord2(T t,String basePath,String YN) {


        try {
            Class<? extends Object> tClass = t.getClass();

            //得到所有属性
            Field[] field = tClass.getDeclaredFields();


            //设置可以访问私有变量
            field[0].setAccessible(true);
            field[1].setAccessible(true);

//            0 目录 1 文件类型
            //获取属性的名字
            String dirtory = field[0].getName();
            //将属性名字的首字母大写
            dirtory = dirtory.replaceFirst(dirtory.substring(0, 1), dirtory.substring(0, 1).toUpperCase());
            //整合出 getId() 属性这个方法
            Method mdirtory = tClass.getMethod("get" + dirtory);
            dirtory=(String) mdirtory.invoke(t);

            System.out.println("++++"+dirtory);
            //获取属性的名字
            String fileType = field[1].getName();
            //将属性名字的首字母大写
            fileType = fileType.replaceFirst(fileType.substring(0, 1), fileType.substring(0, 1).toUpperCase());
            //整合出 getId() 属性这个方法
            Method mfileType = tClass.getMethod("get" + fileType);
            fileType=(String) mfileType.invoke(t);

            System.out.println("---"+fileType);



            VelocityInitializer.initVelocity();

            VelocityContext ctx = new VelocityContext();

            System.out.println(t.toString());
            ctx.put("entity",t);


                        // 获取模板列表

            String wordTemplete="";

        if("accept".equals(dirtory)){
            wordTemplete= "vm/word/accept.docx.vm";

        }else if("register".equals(dirtory)){
            wordTemplete= "vm/word/register.doc.vm";

        }else if("report".equals(dirtory)){
            if ("yes".equals(YN)){
                wordTemplete= "vm/word/reportYes.docx.vm";

            }else if ("no".equals(YN)){
                wordTemplete= "vm/word/reportNo.docx.vm";

            }

        }


        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        String fileString=basePath+"/"+dirtory;
        File dir=new File(fileString);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file = new File(dir, uuid+"."+fileType);
//        if (!file.exists()) {
//            file.createNewFile();
//        }
        System.out.println(fileString);
//      StringWriter sw = new StringWriter();
        Writer sw = new FileWriter(file);

        Template tpl = Velocity.getTemplate(wordTemplete, Constants.UTF8);
        tpl.merge(ctx, sw);
        System.out.println(" template : " + sw );
        sw.flush();
        sw.close();
        System.out.println("over");


            return uuid;

        } catch (Exception e) {

            return null;
        }
    }



    //原生word
    /**
    * @Description:
    * @Param: [basePath , wordTempleteName, wordReplaceParams]
    * @return: java.lang.String
    * @Author: 张泽望
    * @Date: 2020/12/3
    */
    public static  String createWord3(String templateWordFullPath,String newsWordPath,Map<String, Object> wordReplaceParams,String templeteName) {

        //传入相应的 模板地址，和输出word地址 和对应map 返回相应文件名称

        try {

            logger.info("调用createWord3");

            System.out.println("templateWordFullPath="+templateWordFullPath);

            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            String fileString=newsWordPath;
            File dir=new File(fileString);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            System.out.println("newsWordPath="+newsWordPath);
            System.out.println("uuid="+uuid);
            System.out.println("wordReplaceParams="+wordReplaceParams.toString());
            WordTemplateFillData word=new WordTemplateFillData(wordReplaceParams, templateWordFullPath, newsWordPath, templeteName) ;
            word.exportWord(wordReplaceParams,  templateWordFullPath,  newsWordPath,  uuid);
            logger.info("生成了新的文件="+uuid);
            return uuid;

        } catch (Exception e) {

            return null;
        }
    }



    //有增加表格行数的情况
    /**
     * @Description:
     * @Param: [basePath , wordTempleteName, wordReplaceParams]
     * @return: java.lang.String
     * @Author: 张泽望
     * @Date: 2020/12/3
     */
    public static  String createWordContineTable(String templateWordFullPath,String newsWordPath,Map<String, Object> wordReplaceParams,List<String> dataList,String templeteName) {

        //传入相应的 模板地址，和输出word地址 和对应map 返回相应文件名称

        try {



            System.out.println("templateWordFullPath="+templateWordFullPath);

            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            String fileString=newsWordPath;
            File dir=new File(fileString);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            System.out.println("newsWordPath="+newsWordPath);
            System.out.println("uuid="+uuid);
            System.out.println("wordReplaceParams="+wordReplaceParams.toString());

//            List<String> dataList=new LinkedList<>();

            WordTemplateFillData word=new WordTemplateFillData(wordReplaceParams, templateWordFullPath, newsWordPath, templeteName) ;
            if (dataList.size()==0){
                dataList.add(" ");
            }
            word.createTableLine(0,5,4,"文号",dataList);
            word.exportWord(wordReplaceParams,  templateWordFullPath,  newsWordPath,  uuid);
            return uuid;

        } catch (Exception e) {

            return null;
        }
    }


    public static boolean checkWordFile(String file){
        File isFile=new File(file);
        logger.info("check file exist:"+file);
        if (isFile.exists()){
            logger.info(file+":exist");
            return  true;
        }else{
            return  false;

        }



    }


    public static byte[] inputStream2ByteArray(InputStream in, boolean isClose) {
        WordTemplateFillData word = new WordTemplateFillData();
        return  word.inputStream2ByteArray(in,isClose);
    }


}
